package com.lft01.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Function: 		ADD FUNCTION.
 * Reason:   		ADD REASON.
 * Date             2020/6/6 13:02
 * <p>
 * Class Name:      NumPrintTest
 * Package Name:    com.lft.thread
 *
 * @author Laifengting
 * @version 1.0.0
 * @since JDK 8
 */
public class NumPrintTest3 {
	public static int num = 0;
	Lock lock = new ReentrantLock();
	final Condition con0 = lock.newCondition();
	final Condition con1 = lock.newCondition();
	
	public void print0() {
		lock.lock();
		try {
			while (num == 0) {
				try {
					con0.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			num--;
			System.out.println(Thread.currentThread().getName() + " 打印 " + num);
			con1.signalAll();
		} finally {
			lock.unlock();
		}
		
	}
	
	public void print1() {
		lock.lock();
		try {
			while (num == 1) {
				try {
					con1.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			num++;
			System.out.println(Thread.currentThread().getName() + " 打印 " + num);
			con0.signalAll();
		} finally {
			lock.unlock();
		}
	}
}
